package com.chen.whereami;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.chen.whereami.History.StroageManager;
import com.chen.whereami.data.LocationItem;
import com.chen.whereami.utils.Utils;

public class WhereAmIActivity extends SherlockActivity {
	TextView mTextView = null;

	AlertDialog mAboutDlg = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// openGPSSettings();
		setContentView(R.layout.main);

		mTextView = (TextView) findViewById(R.id.textView);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		ActionBar.Tab tabA = actionBar.newTab().setText("A Tab");
		ActionBar.Tab tabB = actionBar.newTab().setText("B Tab");
		ActionBar.Tab tabC = actionBar.newTab().setText("C Tab");
	}

	@Override
	protected void onPause() {
		super.onPause();
		uninitLocation();
	}

	@Override
	protected void onResume() {
		super.onResume();
		initLocation();
	}

	private ShareActionProvider mShareActionProvider;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		MenuItem actionItem = menu.findItem(R.id.menu_share);
		mShareActionProvider = ((ShareActionProvider) (actionItem.getActionProvider()));
		mShareActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
		setShareIntent();
		return true;
	}

	void setShareIntent() {
		if (null == mShareActionProvider)
			return;
		mShareActionProvider.setShareIntent(getDefaultShareIntent());
	}

	Intent getDefaultShareIntent() {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(
			Intent.EXTRA_SUBJECT,
			getResources().getString(R.string.share_title, "2012"));
		intent.putExtra(Intent.EXTRA_TEXT, mCurrentLocation);
		return intent;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.id_menu_about:
			showAboutDlg();
			break;

		case R.id.id_menu_history:
			showHistoryActivity();
			break;

		case R.id.id_menu_copy:
			Utils.saveToClipboard(WhereAmIActivity.this, mCurrentLocation);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	void showHistoryActivity() {
		Intent intent = new Intent();
		intent.setClass(this, HistoryActivity.class);
		startActivity(intent);
	}

	private boolean showAboutDlg() {
		if (null == mAboutDlg) {
			mAboutDlg = new AlertDialog.Builder(this).setIcon(
				R.drawable.menu_about_icon)
					.setTitle(R.string.about_title)
					.setMessage(
						this.getResources().getString(
							R.string.about_this_product))
					.create();
		}

		if (null == mAboutDlg) {
			return false;
		}
		mAboutDlg.show();
		return true;
	}

	void initLocation() {
		LocationManager mgr = (LocationManager) getSystemService(LOCATION_SERVICE);// 获取LocationManager的一个实�?
		if (null == mgr)
			return;
		boolean gpsEnable = mgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
		boolean networkEnable = mgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

		if (!gpsEnable && !networkEnable) {
			mTextView.setText("请打GPS或网络，再重试");
			return;
		}
		if (gpsEnable)
			mgr.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 10000, 0, mLocationListener);
		if (networkEnable) {
			mgr.removeUpdates(mLocationListener);
			mgr.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 10000, 0, mLocationListener);
		}
	}

	void uninitLocation() {
		LocationManager mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
		if (null == mgr)
			return;
		mgr.removeUpdates(mLocationListener);
	}

	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
			return;
		}
		Toast.makeText(this, "请开启GPS", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	}

	String mCurrentLocation = "";

	void updateToStroage(LocationItem item) {
		StroageManager.getInstance().getHistoryDB().insert(item);
	}

	LocationListener mLocationListener = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
			String latitude = Double.toString(location.getLatitude());// 经度
			String longitude = Double.toString(location.getLongitude());// 纬度
			String altitude = Double.toString(location.getAltitude());// 海拔
			String latLongString = null;
			if (location != null) {
				double lat = location.getLatitude();
				double lng = location.getLongitude();

				Geocoder geocoder = new Geocoder(WhereAmIActivity.this);
				// Geocoder geocoder = new Geocoder(this, Locale.CHINA);
				List places = null;

				try {
					// Thread.sleep(2000);
					places = geocoder.getFromLocation(
						location.getLatitude(), location.getLongitude(), 5);
					// Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}

				String placename = "";
				if (places != null && places.size() > 0) {
					placename = ((Address) places.get(0)).getAddressLine(1)
							+ "  "
							+ ((Address) places.get(0)).getAddressLine(2);
				}

				latLongString = "纬度:" + lat + "\r\n" + "经度:" + lng + "\r\n"
						+ placename;
				// Toast.makeText(WhereAreYouActivity.this, placename,
				// Toast.LENGTH_LONG).show();
			} else {
				latLongString = "无法获取地理信息";
			}
			mCurrentLocation = latLongString;
			mTextView.setText(latLongString);
			setShareIntent();
			// 更新到存储Manager
			updateToStroage(new LocationItem(latitude, longitude, altitude,
				latLongString));
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}
	};
}